package com.macaline.nio;

import org.junit.jupiter.api.Test;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Date;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class Demo2 {




    // 服务端代码
    @Test
    public void server() throws Exception {

        // 获取服务端通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        // 切换非阻塞
        serverSocketChannel.configureBlocking(false);

        // 创建buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        // 绑定端口
        serverSocketChannel.bind(new InetSocketAddress(9999));

        // 获取选择器
        Selector selector = Selector.open();

        // 注册到通道
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (selector.select() > 0){
            Set<SelectionKey> selectededKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectededKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey next = iterator.next();
                if(next.isAcceptable()){
                    SocketChannel accept = serverSocketChannel.accept();
                    accept.configureBlocking(false);
                    accept.register(selector, SelectionKey.OP_READ);
                }else if(next.isReadable()){
                    SocketChannel channel = (SocketChannel) next.channel();
                    ByteBuffer allocate = ByteBuffer.allocate(1024);
                    int length = 0;
                    while ((length = channel.read(allocate)) > 0){
                        allocate.flip();
                        System.out.println(new String(allocate.array(), 0, length));
                        allocate.clear();
                    }
                }
                iterator.remove();
            }
        }


    }

    public static void main(String[] args) throws Exception {
        client();
    }


    // 客户端代码
    @Test
    public static void client() throws Exception {
        // 创建链接
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9999));

        // 切换非阻塞
        socketChannel.configureBlocking(false);

        // 创建buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            String s = scanner.next();

            // 写入buffer
            buffer.put((new Date().toString() + "----" + s).getBytes());

            // 模式切换
            buffer.flip();

            // 写入通道
            socketChannel.write(buffer);

            // 关闭
            buffer.clear();
        }
    }

}
